var path = require('path')
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
// const apiMocker = require('mocker-api')

// 查找路径
function resolve (dir) {
  return path.join(__dirname, dir)
}

const env = process.env.NODE_ENV
// console.log('analyze',process.env.npm_config_analyze)

module.exports = {
  publicPath: '/',
  productionSourceMap: false, // 是否在构建生产包时生成 sourceMap 文件，false将提高构建速度
  css: {
    loaderOptions: {
      less: {
        modifyVars: {},
        javascriptEnabled: true
      }
    },
    extract: true
  },
  lintOnSave: 'warning', // 是否在保存时检查eslint
  chainWebpack: config => {
    // 配置别名
    config.resolve.alias
      .set('@', resolve('src'))
      .set('@assets', resolve('src/assets'))
      .set('@api', resolve('src/api'))
      .set('@components', resolve('src/components'))
      .set('@config', resolve('src/config'))
      .set('@store', resolve('src/store'))
      .set('@utils', resolve('src/utils'))
      .set('@http', resolve('src/http'))

    config.optimization.minimize(true) // 最小化压缩
    config.optimization.splitChunks({
      // 分割代码
      chunks: 'all'
    })
  },
  configureWebpack: config => {
    // 入口文件
    // config.entry.app = ['babel-polyfill', './src/main.js']
    const pluginArr = []

    // 只有打包生产环境才需要将console删除
    if (env === 'production') {
      config.optimization.minimizer[0].options.terserOptions.compress.warnings = false
      config.optimization.minimizer[0].options.terserOptions.compress.drop_console = true
      config.optimization.minimizer[0].options.terserOptions.compress.drop_debugger = true
      config.optimization.minimizer[0].options.terserOptions.compress.pure_funcs = [
        'console.log'
      ]
    }
    if (process.env.npm_config_analyze) {
      pluginArr.push(new BundleAnalyzerPlugin())
    }
    return {
      plugins: pluginArr
    }
  },
  devServer: {
    // before (app) {
    // 模拟mock数据
    // apiMocker(app, path.resolve(__dirname, './mock/index.js'), {
    // proxy: {
    //   '/aikq-api': 'http://10.108.4.105:8080/aikq-api',
    // }
    // })
    // },
    disableHostCheck: true,
    host: '0.0.0.0', // 要设置当前访问的ip 否则失效
    // open: true, // 浏览器自动打开页面
    proxy: { // 代理
      '/api': {
        target: 'http://xxx.com/x-api',
        ws: true,
        changeOrigin: true,
        pathRewrite: {
          '^/x-api': ''
        }
      }
    }
  },
  parallel: require('os').cpus().length > 1 // 构建时开启多进程处理babel编译
}
